/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package casino;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * The table holds all the bets placed by players.
 * 
 * @author amaghfur
 * @since v1.0
 */
public class Table {
    
    /** table limits (default to 1000) */
    private Rational limit = new Rational(1000);
    /** list of bets currently active */
    private List<Bet> bets;
    
    /**
     * Class constructor. Also creates an empty LinkedlList of bets.
     */
    public Table() {
        bets = new LinkedList<>();
    }
    
    /**
     * Getter for bets
     * 
     * @return  list of bets
     */
    public List<Bet> getBets() {
        return bets;
    }
    
    /** setter for table limit */
    public void setLimit(Rational newLimit) {
        limit = newLimit;
    }
    
    /**
     * Checks to see if the newBet is within the table limits. In Roulette, the
     * total amount of all bets on the table must be less than or equal to the 
     * table limits.
     * 
     * @param newBet
     * @return 
     */
    public boolean isValid(Bet newBet) {
        Rational betTotal = new Rational(0);
        Iterator<Bet> itBets = bets.iterator();
        while(itBets.hasNext()) {
            betTotal = betTotal.plus(itBets.next().getAmountBet()) ;
        }
        betTotal = betTotal.plus(newBet.getAmountBet());
        if (betTotal.lessThanOrEqual(limit))
            return true;
        else
            return false;
    }
    
    /**
     * Used to place a bet on this table.
     * 
     * @param newBet                a bet to be placed on the table
     * @throws InvalidBetException  thrown if bet does not meet table limits
     */
    public void placeBet(Bet newBet) throws InvalidBetException {
        if (isValid(newBet) == true)
            bets.add(newBet);
        else
            throw new InvalidBetException(newBet.getAmountBet());
    }
    
    /**
     * Returns a listIterator for the collection of bets on this table. Will be used
     * to remove bets from the table and update the current collection of bets.
     * 
     * @return  a listIterator for the collection of bets
     */
    public Iterator<Bet> iterator() {
        return bets.listIterator();
    }
    
    /**
     * Returns a string representation of all the current bets on this table.
     * 
     * @return  string representation
     */
    @Override
    public String toString() {
        Iterator<Bet> itBets = bets.iterator();
        String stringBuffer = "";
        while(itBets.hasNext()) {
            stringBuffer += itBets.next().toString() + "\n";
        }
        return stringBuffer;
    }
    
}
